package com.example.myapplication.Fragment

import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.Adapter.TodoAdapter
import com.example.myapplication.Model.TodoModel
import com.example.myapplication.R
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.util.*

class TodoFragment : Fragment() {

    private val todoList = mutableListOf<TodoModel>()
    private lateinit var adapter: TodoAdapter
    private lateinit var sharedPreferences: SharedPreferences

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_todo, container, false)

        val recyclerView: RecyclerView = view.findViewById(R.id.recycler_view)
        recyclerView.layoutManager = LinearLayoutManager(context)
        adapter = TodoAdapter(todoList, object : TodoAdapter.OnItemClickListener {
            override fun onItemDelete(todo: TodoModel) {
                deleteTodo(todo)
            }

            override fun onItemEdit(todo: TodoModel) {
                showEditDialog(todo)
            }

            override fun onItemComplete(todo: TodoModel, isCompleted: Boolean) {
                todo.isCompleted = isCompleted
                saveTodos()
            }
        })
        recyclerView.adapter = adapter

        // Add sample data
        loadTodos()

        // Set up add button click listener
        val addButton: Button = view.findViewById(R.id.add_button)
        addButton.setOnClickListener {
            showAddDialog()
        }

        return view
    }

    private fun loadTodos() {
        sharedPreferences = requireActivity().getPreferences(Context.MODE_PRIVATE)
        val json = sharedPreferences.getString("todos", null)
        if (json != null) {
            val type = object : TypeToken<List<TodoModel>>() {}.type
            todoList.addAll(Gson().fromJson(json, type))
        } else {
            // Add sample data
            todoList.add(TodoModel("1", "Buy groceries", "Milk, Bread, Eggs", false))
        }
        adapter.notifyDataSetChanged()
    }

    private fun saveTodos() {
        val json = Gson().toJson(todoList)
        val editor = sharedPreferences.edit()
        editor.putString("todos", json)
        editor.apply()
    }

    private fun deleteTodo(todo: TodoModel) {
        todoList.remove(todo)
        adapter.notifyDataSetChanged()
        saveTodos()
    }

    private fun showAddDialog() {
        val dialogView = layoutInflater.inflate(R.layout.dialog_add_todo, null)
        val titleEditText: EditText = dialogView.findViewById(R.id.title_edit_text)
        val descriptionEditText: EditText = dialogView.findViewById(R.id.description_edit_text)
        val dialog = android.app.AlertDialog.Builder(requireContext())
            .setView(dialogView)
            .setPositiveButton("Add") { _, _ ->
                val title = titleEditText.text.toString()
                val description = descriptionEditText.text.toString()
                val newId = UUID.randomUUID().toString()
                val newTodo = TodoModel(newId, title, description, false)
                todoList.add(newTodo)
                adapter.notifyItemInserted(todoList.size - 1)
                saveTodos()
            }
            .setNegativeButton("Cancel", null)
            .create()
        dialog.show()
    }

    private fun showEditDialog(todo: TodoModel) {
        val dialogView = layoutInflater.inflate(R.layout.dialog_add_todo, null)
        val titleEditText: EditText = dialogView.findViewById(R.id.title_edit_text)
        val descriptionEditText: EditText = dialogView.findViewById(R.id.description_edit_text)
        titleEditText.setText(todo.title)
        descriptionEditText.setText(todo.description)
        val dialog = android.app.AlertDialog.Builder(requireContext())
            .setView(dialogView)
            .setPositiveButton("Save") { _, _ ->
                todo.title = titleEditText.text.toString()
                todo.description = descriptionEditText.text.toString()
                adapter.notifyDataSetChanged()
                saveTodos()
            }
            .setNegativeButton("Cancel", null)
            .create()
        dialog.show()
    }
}